<?
/*
    topGames: an iRC games bot
    Copyright (C) 2008 Marcos García <marcosgdf@gmail.com>
    
	This file is part of topGames

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

define('MASTER_DIR',dirname(__FILE__));

require(MASTER_DIR.'/config.php');
require(MASTER_DIR.'/class.misc.php');

$tg = new topgames;
if (isset($_GET["q"])) {
	if (!isset($_SERVER['PHP_AUTH_USER'])) {
  		header('WWW-Authenticate: Basic realm="miniDB topgames"');
  		header('HTTP/1.0 401 Unauthorized');
 	}
 	else {
  		$tg->dbConnect();
  		$tg->dbSelect(DB_NAME);
  		$userExists = $tg->dbSend("SELECT pass FROM ".DB_PREFIX."users WHERE `user`='{$_SERVER['PHP_AUTH_USER']}'");
  		$result = mysql_num_rows($userExists);
  		if ($result) {
  			$password = mysql_result($userExists,0);
   			if (md5($_SERVER['PHP_AUTH_PW']) != $password || (!$password)) {
    			header('WWW-Authenticate: Basic realm="miniDB topgames"');
    			header('HTTP/1.0 401 Unauthorized');
   			}
   			else {
    			$apiQuery = $_GET["q"];
    			$params = explode(' ', $apiQuery);
    			$action = $params[0];
    			if ($action == "SELECT") select(strtolower($params[1]),strtolower(mysql_real_escape_string($params[2])));
    			if ($action == "UPDATE") update(strtolower($params[1]),mysql_real_escape_string($params[2]),mysql_real_escape_string($params[3]));
    			if ($action == "CREATE") create(mysql_real_escape_string($params[1]));
    			if ($action == "DELETE") delete(mysql_real_escape_string($params[1]));
	  			//if ($cmd == "RAE") { rae($query_explode[1]); } <- todavía no implementado en el bot, por lo tanto no se desarrolla
   			}
  		}
  		else die('Error 001: Unauthorized');
 	}
}
 
function create($nick) {
 	global $tg;
 	$nickExists = $tg->isNickInDB($nick);
 	if ($nickExists) die('Error 005: User exists');
 	else {
  		$tg->dbSend("INSERT INTO ".DB_PREFIX."data SET `nick`='$nick'");
  		$playerId = mysql_insert_id();
  		$moneyfd = fopen(MASTER_DIR."/dinero/$playerId.db",'wt');
  		$bonosfd = fopen(MASTER_DIR."/bonos/$playerId.db",'wt');
  		fwrite($moneyfd,0);
  		fwrite($bonosfd,0);
  		fclose($moneyfd);
  		fclose($bonosfd);
  		$tg->dbSend("INSERT INTO ".DB_PREFIX."bytes_d SET `jid`='$playerId', `len`='1'");
  		$tg->dbSend("INSERT INTO ".DB_PREFIX."bytes_b SET `jid`='$playerId', `len`='1'");
  		echo 'OK';
 	}
}

function delete($nick) {
 	global $tg;
 	$nickExists = $tg->isNickInDB($nick);
 	if (!$nickExists) die("Error 006: User doesn't exists");
 	else {
  		$tg->dbSend("DELETE FROM ".DB_PREFIX."bytes_b WHERE `jid`='$nickExists'");
  		$tg->dbSend("DELETE FROM ".DB_PREFIX."bytes_d WHERE `jid`='$nickExists'");
  		$tg->dbSend("DELETE FROM ".DB_PREFIX."data WHERE `nick`='$nick'");
  		unlink(MASTER_DIR."/dinero/$nickExists.db");
  		unlink(MASTER_DIR."/bonos/$nickExists.db");
  		echo 'OK';  
 	}
}
 
function update($type,$nick,$data) {
 	global $tg;
 	$playerId = $tg->isNickInDB($nick);
 	if (!$playerId) die("Error 006: User doesn't exists");
 	else {
  		if ($type == 'dinero') {
   			$filePath = MASTER_DIR."/dinero/$playerId.db";
   			if (!file_exists($filePath)) die("Error 002: File doesn't exists");
   			else {
    			if (!is_writable($filePath)) die("Error 004: File isn't writable");
    			else {
     				$filefd = fopen($filePath,'wt');
	 				fwrite($filefd,$data);
	 				fclose($filefd);
	 				$dataLength = strlen($data);
	 				$tg->dbSend("UPDATE ".DB_PREFIX."bytes_d SET len='$dataLength' WHERE `jid`='$playerId'");
	 				echo 'OK';
    			}
   			}
  		} elseif ($type == 'bonos') {
   			$filePath = MASTER_DIR."/bonos/$playerId.db";
   			if (!file_exists($filePath)) die("Error 002: File doesn't exists");
   			else {
    			if (!is_writable($filePath)) die("Error 004: File isn't writable");
    			else {
     				$filefd = fopen($filePath,'wt');
     				fwrite($filefd,$data);
     				fclose($filefd);
	 				$dataLength = strlen($data);
	 				$tg->dbSend("UPDATE ".DB_PREFIX."bytes_b SET `len`='$dataLength' WHERE `jid`='$playerId'");
	 				echo 'OK';
    			}
   			}
  		}
 	}
}
 
function select($type,$nick) {
 	global $tg;
 	$playerId = $tg->isNickInDB($nick);
 	if (!$playerId) die("Error 006: User doesn't exists");
 	else {
  		if ($type == 'dinero') {
   			$filePath = MASTER_DIR."/dinero/$playerId.db";
   			if (!file_exists($filePath)) die("Error 002: File doesn't exists");
   			else {
    			if (!is_readable($filePath)) die("Error 003: File isn't readable");
    			else {
     				$money = file($filePath);
     				$money = $money[0];
     				if (!is_numeric($money)) die("Error 022: Error when trying to read from the file");
     				else {
     					echo $money;
     				}
    			}
   			}
  		} elseif ($type == 'bonos') {
   			$filePath = MASTER_DIR."/bonos/$playerId.db";
   			if (!file_exists($filePath)) die("Error 002: File doesn't exists");
   			else {
    			if (!is_readable($filePath)) die("Error 003: File isn't readable");
    			else {
     				$bonos = file($filePath);
     				$bonos = $bonos[0];
     				if (!is_numeric($bonos)) die("Error 022: Error when trying to read the file");
	 				else {
	 					echo $bonos;
	 				}
    			}
   			}
  		}
 	}
}
 
/*function rae($word) { <- todavía no implementado en el bot, por lo tanto es innecesaria esta función
  $mysql = new mysql;
  $mysql->connect();
  global $_CFG;
  $if = $mysql->query('SELECT id FROM '.$_CFG["table_prefix"].'rae WHERE palabra=\''.mysql_real_escape_string_string($word).'\'',0,1,0);
  if ($if == 1) {
   $ifi = $mysql->query('SELECT valid FROM '.$_CFG["table_prefix"].'rae WHERE palabra=\''.mysql_real_escape_string_string($word).'\'',1,0,0);
   echo $ifi[0];
  }
  else {
   $web = 'http://www.wordreference.com/definicion/'.urlencode($word).'';
   $ch = curl_init();
   curl_setopt ($ch, CURLOPT_URL, $web);
   curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);
   curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
   $bufer = curl_exec($ch);
   curl_close($ch);
   $exploder = explode("<",$bufer);
   if (trim($exploder[113]) == trim('p align="center">No se ha encontrado definicion para \''.$word.'\' en el diccionario espa�ol.')) { $no_existe = 1; }
    if (!isset($no_existe)) {
	 $mysql->query('INSERT INTO '.$_CFG["table_prefix"].'rae SET palabra=\''.mysql_real_escape_string_string($word).'\', valid=\'1\'',0,0,0);
	 echo 1; 
	}
    else { 
	 $mysql->query('INSERT INTO '.$_CFG["table_prefix"].'rae SET palabra=\''.mysql_real_escape_string_string($word).'\', valid=\'0\'',0,0,0);
	 echo 0;
	}
   }
 }*/
?>